﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lib.CommonForm;
using WeifenLuo.WinFormsUI.Docking;

namespace AUI
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();

            //
            Init_Control();
            //
            this.Text = Globals.Application_GetTitle();
            Program.m_frmMain = this;
            //Program.m_toolbarMain = this.toolStrip;
            Program.m_menuMain = this.menuStrip;
            //


            //slblVersion.Text = "Phiên bản: " + Globals.assemblyVersion;
            //slblUserName.Text = "";
            //slblUserName.Visible = false;
            //slblAddressIP.Text = "";
            //slblAddressIP.Visible = false;
            //ShowTime();

            ////dockPanel1.BackgroundImage = global::UI.Properties.Resources.IAS_png;
            //dockPanel1.BackgroundImageLayout = ImageLayout.Center;
            ////dockPanel1.BackColor = _backgroundColor;
            //dockPanel1.ContentAdded += new EventHandler<DockContentEventArgs>(dockPanel1_ContentAdded);
            //dockPanel1.ContentRemoved += new EventHandler<DockContentEventArgs>(dockPanel1_ContentRemoved);

            ////MenuStrip_EnabledChanged(menuStrip1);

            //Timer timerTime = new Timer();
            //timerTime.Enabled = true;
            //timerTime.Interval = 1000;
            //timerTime.Tick += new EventHandler(timerTime_Tick);

        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            FormGlobals.dockPanel = dockPanel;
            //Common.InitResource();

            //
            this.Show();
            //
        }
        private void frmMain_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            try
            {
                if (e.CloseReason == CloseReason.UserClosing)
                {
                    e.Cancel = !(FormGlobals.Message_Confirm("Are you sure you want to exit this program?"));
                    if (!e.Cancel)
                    {
                        e.Cancel = true;
                        Application.Exit();
                    }
                }
            }
            catch
            {

            }
        }
        internal void LockOut()
        {
            if (InvokeRequired)
            {
                this.Invoke(new MethodInvoker(LockOut));
                return;
            }
            //Close all form
            for (int i = Application.OpenForms.Count - 1; i >= 0; i--)
            {
                Form f = Application.OpenForms[i];
                if (f.Name != this.Name)
                {
                    f.Close();
                    f.Dispose();
                }
            }
            //
            Menu_SetEnabled(menuStrip, false);
            emnuLogin.Enabled = true;
            //
            SignIn();
        }

        internal void SignOut()
        {
            //if (Common.User_Info != null)
            //{
                if (!(FormGlobals.Message_Confirm("Are you sure you want to sign out?", false)))
                {
                    return;
                }
            //}
            LockOut();
        }
        private Boolean m_IsStartup = true;
        internal Boolean SignIn()
        {
            Boolean retVal = false;
            //if (Common.popupNotifier==null) Common.popupNotifier = popupNotifier;
            //Check client config when application startup
            if (m_IsStartup)
            {
                m_IsStartup = false;
                //FormGlobals.App_ProgressShow(delegate()
                //{
                //    retVal = DataConnect.Check_Connect(Globals.Application_GetConfig("LoginConnect"));
                //}, "Checking client config");
                //if (!retVal)
                //{
                //    return (new frmClientConfig()).ShowDialog() == DialogResult.OK;
                //}
            }
            //
            frmLogin f = new frmLogin();
            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Application.DoEvents();
                //if (Common.User_Info.Must_Change_Pass)
                //{
                //    Common.Message_Information("Your password is expired. Please change your password before using this program");
                //    frmChangePass fChangePwd = new frmChangePass();
                //    fChangePwd.txtOldPass.Text = f.txtUserPassword.Text;
                //    fChangePwd.txtOldPass.Enabled = false;
                //    if (fChangePwd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                //    {
                //        Common.User_Info.Must_Change_Pass = false;
                //        retVal = true;
                //    }
                //}
                //else
                    retVal = true;
                //
                Splash.Show(PostLogin);
                this.Activate();
            }
            else
            {
                emnuLogin.Enabled = true;
            }
            return retVal;
        }
        //do something after login
        private void PostLogin()
        {
            //Reading system config
            FormGlobals.App_Init();
            //Setting menu permission
            //Menu_SetByPermission(menuStrip);
            //
            //emnuLogout.Enabled = true;
            emnuLogin.Enabled = false;
            emnuChangePass.Enabled = true;
            //emnuToolBarOption.Enabled = true;
            //(new ToolBarConfig()).SetLoginToolBar();
            //
            FormGlobals.App_IdleHandle(LockOut, TimeSpan.FromMinutes(FormGlobals.CS_IDLE_TIMEOUT));
            //Init Status bar
            //statusStrip.Items.Clear();
            //Status_AddItem("", Common.User_Info.User_Name + " - " + Common.User_Info.User_Fullname);
            //statusStrip.Items.Add(new ToolStripSeparator());
            //Status_AddItem("Unit:", (String.IsNullOrEmpty(Common.User_Info.Unit_Name) ? "N/A" : Common.User_Info.Unit_Name));
            //statusStrip.Items.Add(new ToolStripSeparator());
            //Status_AddItem("Login:", Common.User_Info.Last_Login.ToString(Globals.CS_EDIT_DATETIME_FORMAT));
            //statusStrip.Items.Add(new ToolStripSeparator());
            //
            ToolStripStatusLabel tsl = new ToolStripStatusLabel();
            tsl.Spring = true;

            //statusStrip.Items.Add(tsl);
            //
            //statusStrip.Items.Add(new ToolStripSeparator());
            //Status_AddItem("Service:", Globals.Application_GetConfig("LoginConnect"));
            //statusStrip.Items.Add(new ToolStripSeparator());
            //Status_AddItem("Product Version:", Application.ProductVersion + " - " + System.IO.File.GetLastWriteTime(Application.ExecutablePath).ToString(Globals.CS_EDIT_DATE_FORMAT));
        }
        private void Init_Control()
        {
            //
            dockPanel.BackColor = FormGlobals.App_GetColor("#3a6ea5");
            //
            System.Windows.Forms.ToolStripItemClickedEventHandler itemClick;
            foreach (ToolStripMenuItem mnuRoot in menuStrip.Items)
            {
                itemClick = null;
                if (mnuRoot.DropDownItems.Count == 0
                    || mnuRoot.Name == emnuItems.Name
                    || mnuRoot.Name == emnuFunction.Name
                    )
                {
                    switch (mnuRoot.Name)
                    {
                        case "emnuItems":
                            modItems.Menu_Init(mnuRoot);
                            break;
                        case "emnuFunction":
                            //modFunction.Menu_Init(mnuRoot);
                            break;
                    }
                    continue;
                }
                switch (mnuRoot.Name)
                {
                    case "emnuSystem":
                        itemClick = new System.Windows.Forms.ToolStripItemClickedEventHandler(modSystem.Menu_DropDownItemClicked);
                        break;
                    case "emnuItems":
                        itemClick = new System.Windows.Forms.ToolStripItemClickedEventHandler(modItems.Menu_DropDownItemClicked);
                        break;
                    case "emnuFunction":
                        itemClick = new System.Windows.Forms.ToolStripItemClickedEventHandler(modItems.Menu_DropDownItemClicked);
                        break;
                    
                    case "imnuHelp":
                        itemClick = mnuHelp_DropDownItemClicked;
                        break;
                }
                if (itemClick != null)
                {
                    Menu_AutoInit(mnuRoot, itemClick);
                }
            }
        }
        void mnuHelp_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                //case "imnuClientConfig":
                //    (new frmClientConfig()).ShowDialog();
                //    break;
            }
        }

        private void Menu_AutoInit(ToolStripMenuItem mnuRoot, ToolStripItemClickedEventHandler itemClick)
        {
            //if (mnuRoot.DropDownItems.Count == 0 || mnuRoot.OwnerItem == null)
            if (mnuRoot.DropDownItems.Count > 0)
                mnuRoot.DropDownItemClicked += itemClick;
            //
            int iIndex = 0;
            foreach (ToolStripItem itmChild in mnuRoot.DropDownItems)
            {
                if (itmChild is ToolStripMenuItem)
                {
                    Menu_AutoInit((ToolStripMenuItem)itmChild, itemClick);
                    iIndex += 1;
                    if (!itmChild.Text.StartsWith("&"))
                    {
                        itmChild.Text = String.Format("&{0}. ", iIndex.ToString("X")) + itmChild.Text;
                    }
                }
            }
        }
        private void Menu_SetEnabled(MenuStrip mnuObject, Boolean bEnabled)
        {
            for (int i = 0; i < mnuObject.Items.Count; i++)
            {
                Menu_SetEnabled((ToolStripMenuItem)mnuObject.Items[i], bEnabled);
            }
        }

        private void Menu_SetEnabled(ToolStripMenuItem obj, Boolean bEnabled)
        {
            int i = 0;
            if (obj.DropDownItems.Count <= 0)
            {
                if (!String.IsNullOrEmpty(obj.Name) && obj.Name.Substring(0, 1) == "i")
                    obj.Enabled = true;
                else
                    obj.Enabled = bEnabled;
            }
            else
            {
                for (i = 0; i < obj.DropDownItems.Count; i++)
                {
                    if ((obj.DropDownItems[i]) is ToolStripMenuItem)
                        Menu_SetEnabled((ToolStripMenuItem)obj.DropDownItems[i], bEnabled);
                }
            }
        }


        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
#if (DEBUG)
            if (keyData == (Keys.Shift | Keys.F6) && this.ActiveMdiChild == null)
            {
                if (FormGlobals.Message_Confirm("Update all menu data"))
                { 
                    //FormGlobals.App_ProgressShow(delegate() { Menu_BuildAll(menuStrip); }, "Updating menu "); 
                }
            }
#endif
            return base.ProcessCmdKey(ref msg, keyData);
        }

        void ShowTime()
        {
            //string _DayofWeek = "";
            //switch (DateTime.Now.DayOfWeek)
            //{
            //    case DayOfWeek.Friday:
            //        _DayofWeek = "Thứ sáu";
            //        break;
            //    case DayOfWeek.Monday:
            //        _DayofWeek = "Thứ hai";
            //        break;
            //    case DayOfWeek.Saturday:
            //        _DayofWeek = "Thứ bảy";
            //        break;
            //    case DayOfWeek.Sunday:
            //        _DayofWeek = "Chủ nhật";
            //        break;
            //    case DayOfWeek.Thursday:
            //        _DayofWeek = "Thứ năm";
            //        break;
            //    case DayOfWeek.Tuesday:
            //        _DayofWeek = "Thứ ba";
            //        break;
            //    case DayOfWeek.Wednesday:
            //        _DayofWeek = "Thứ tư";
            //        break;
            //    default:
            //        break;
            //}
            //_DayofWeek = _DayofWeek + " " + DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");

            slblDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            slblTime.Text = DateTime.Now.ToString("HH:mm:ss");
        }

        void timerTime_Tick(object sender, EventArgs e)
        {
            ShowTime();
        }

        void dockPanel1_ContentRemoved(object sender, WeifenLuo.WinFormsUI.Docking.DockContentEventArgs e)
        {
            //throw new NotImplementedException();
        }

        void dockPanel1_ContentAdded(object sender, WeifenLuo.WinFormsUI.Docking.DockContentEventArgs e)
        {
            //throw new NotImplementedException();
        }


     

        private void mnuExit_Click(object sender, EventArgs e)
        {
            if (FormGlobals.Message_Confirm(UIMessage.QUESTION_EXIT))
            {
                this.Dispose();
                this.Close();
                Application.Exit();
            }
        }

        private void mnuLogin_Click(object sender, EventArgs e)
        {
            //frmLogin fLogin = new frmLogin();
            //if (fLogin.ShowDialog(this) == DialogResult.OK)
            //{
            //    if (FormGlobals.strUserName.Length > 0)
            //    {
            //        foreach (Form fChild in this.MdiChildren)
            //        {
            //            fChild.Close();
            //        }

            //        EnableMenuMain(true);
                    
            //        ShowMenuByRole();

            //        slblUserName.Text = FormGlobals.strUserName;
            //        slblUserName.Visible = true;

            //        ConnectLog rs = new ConnectLog();

            //        slblAddressIP.Text = rs.ServiceAddress;
            //        slblAddressIP.Visible = true;
            //    }
            //}
        }
        void EnableMenuMain(bool isok)
        {
            emnuItems.Enabled = isok;
            emnuFunction.Enabled = isok;
            ShowShortcutKeys();
        }
        void ShowShortcutKeys()
        {
            //Nếu không làm theo cách này thì khi nhấn phím tắt, chức năng tương ứng sẽ hiện ra ngay cả khi menu cha bị ẩn
            //Ỏ đây menu cha là: menu Danh mục, menu Chức năng, menu Quản lý, menu Báo cáo
            //Nhưng menu cha ko bị ẩn thì không cần làm thế này
            //Ở đây menu luôn hiện là: menu hệ thống, menu Trợ giúp thì không cần xét lại ShortcutKeys

            if (emnuItems.Enabled)
            {
                mnuBranchList.ShortcutKeys = Keys.None;
                mnuDepartmentList.ShortcutKeys = Keys.None;

                //mnuBranchList.ShortcutKeys = (Keys.Alt | Keys.D1);
                //mnuDepartmentList.ShortcutKeys = (Keys.Alt | Keys.D2);
            }
            else
            {
                mnuBranchList.ShortcutKeys = Keys.None;
                mnuDepartmentList.ShortcutKeys = Keys.None;
            }
        }
        private void ShowMenuByRole()
        {
            //Xét lại các menu theo quyền

            //Hệ thống
            if (FormGlobals.isAdmin)
            {
                mnuRoleList.Enabled = true;
                mnuInformation.Enabled = true;
                emnuChangePass.Enabled = true;
                mnuUsersList.Enabled = true;
            }
            else
            {
                //mnuRoleList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("VaiTro").ViewRight;
                //mnuInformation.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("CongTy").ViewRight;
                //mnuChangePassword.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("DoiMatKhau").ViewRight;
                //mnuUsersList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("NguoiDung").ViewRight;
            }

            

            //Danh mục
            //mnuBranchList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("DonVi").ViewRight;
            //mnuDepartmentList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("BoPhan").ViewRight;
            //mnuEmployeesList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("NhanVien").ViewRight;
            //mnuUnitsList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("NhanVien").ViewRight;
            //mnuDrugsList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("Thuoc").ViewRight;
            //mnuDrugTypesList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("LoaiThuoc").ViewRight;
            //mnuOrderTypesList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("LoaiDonHang").ViewRight;
            //mnuSuppliersList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("NhaCungCap").ViewRight;
            //mnuCustomersList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("KhachHang").ViewRight;

            //Chức năng
            mnuOrdersList.Enabled = tbl_RoleRight_Controller.Instance().GetInfo("DonHang").ViewRight;
        }


        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Form1 f = new Form1(FormGlobals. Form_GetTabText(sender));

            if (!FormGlobals.Form_FindInTab(this,FormGlobals.Form_GetTabText(sender)))
            {
                //f.RightToLeftLayout = true;
                //f.Show(this.dockPanel1, DockState.DockRightAutoHide);
                f.Show(this.dockPanel);
            }
        }


        private void mnuEmployees_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmUserList"))
            {
                frmEmployeesList f = new frmEmployeesList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuRoleList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmRolesList"))
            {
                frmRolesList f = new frmRolesList(FormGlobals.Form_GetTabText(sender));
                f.Show(this.dockPanel);
            }
        }

        private void mnuEmployeesList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmEmployeesList"))
            {
                frmEmployeesList f = new frmEmployeesList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuUsersList_Click(object sender, EventArgs e)
        {
            //if (!FormGlobals.Form_FindInTab(this,"frmUsersList"))
            //{
            //    frmUsersList f = new frmUsersList(FormGlobals.Form_GetTabText(sender), false, 0, "");
            //    f.Show(this.dockPanel);
                
            //}
            new frmUsersList().Show_Form(FormGlobals.Form_GetTabText(sender), false, 0, "");
        }

        private void mnuChangePassword_Click(object sender, EventArgs e)
        {
            frmChangePassword f = new frmChangePassword();
            f.ShowDialog();
        }

        private void mnuInformation_Click(object sender, EventArgs e)
        {
            frmInformation f = new frmInformation();
            f.ShowDialog();
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void mnuBranchList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmBranchList"))
            {
                frmBranchList f = new frmBranchList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuDepartmentList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmDepartmentList"))
            {
                frmDepartmentList f = new frmDepartmentList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuUnitsList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmUnitsList"))
            {
                frmUnitsList f = new frmUnitsList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuOrderTypesList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmOrderTypesList"))
            {
                frmOrderTypesList f = new frmOrderTypesList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuDrugTypesList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmDrugTypesTree"))
            {
                frmDrugTypesTree f = new frmDrugTypesTree();
                f.Show(this.dockPanel);
            }

            //if (!FormGlobals.Form_FindInTab(this,"frmDrugTypesList"))
            //{
            //    frmDrugTypesList f = new frmDrugTypesList(FormGlobals.Form_GetTabText(sender), false, 0, "");
            //    f.Show(this.dockPanel1);
            //}
        }

        private void mnuSuppliersList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmSuppliersList"))
            {
                frmSuppliersList f = new frmSuppliersList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

        private void mnuCustomersList_Click(object sender, EventArgs e)
        {
            if (!FormGlobals.Form_FindInTab(this,"frmCustomersList"))
            {
                frmCustomersList f = new frmCustomersList(FormGlobals.Form_GetTabText(sender), false, 0, "");
                f.Show(this.dockPanel);
            }
        }

    }
}
